package com.hefan.user.dao;

import com.hefan.common.orm.dao.CommonDaoImpl;
import org.springframework.stereotype.Repository;

import java.util.concurrent.SynchronousQueue;

/**
 * Created by lxw on 2016/9/27.
 */
@Repository
public class UserSequenceDao extends CommonDaoImpl {

    /**
     * 获取当前seqVal
     * @param seqType
     * @return
     */
    public long querySeqVal(int seqType) {
        String sql = "select current_seq from sys_sequence where seq_type=?";
        Long currentSeq  = getJdbcTemplate().queryForObject(sql, new Object[]{seqType}, Long.class);
        if(currentSeq == null) {
            return 0L;
        }
        return currentSeq.longValue();
    }

    /**
     * 根据自增序列进行更新
     * @param seqType
     * @param maxSeqVal
     * @param mainSeqVal
     * @return
     */
    public int updateSeqVal(int seqType, long maxSeqVal, long mainSeqVal) {
        String sql = "update sys_sequence set current_seq=?,min_seq=?,max_seq=? where seq_type=? and  min_seq< ? and max_seq< ?";
        return this.update(sql,new Object[] {maxSeqVal,mainSeqVal,maxSeqVal,seqType,mainSeqVal,maxSeqVal});
    }

    /**
     * 获取一组自增序列的最大值
     * @param seqType
     * @param seqNum 获取个数
     * @return
     */
    public long getNextSeqVal(int seqType,long seqNum) {
        long cSeqVal = querySeqVal(seqType);
        if(cSeqVal == 0) {
            return 0;
        }
        long maxSeqVal = cSeqVal+seqNum;
        long mainSeqVal = maxSeqVal- seqNum + 1;
        while (updateSeqVal(seqType,maxSeqVal,mainSeqVal) == 0){
            return getNextSeqVal(seqType,seqNum);
        }
        return maxSeqVal;
    }

    /**
     * 更新seq的当前值
     * @param seqType
     * @param seqVal
     * @return
     */
    public int updateCurrentSeq(int seqType, long seqVal) {
        String sql = "update sys_sequence set current_seq=? where seq_type=?";
        return this.update(sql,new Object[] {seqVal,seqType});
    }


    /**
     * 获取drds的sequece索引
     * @param sequenceNam
     * @return
     */
    public long getSequenceFromDrdsBySequenceName(String sequenceNam) {
        String sql = "select "+sequenceNam+".nextVal from dual";
        return getJdbcTemplate().queryForObject(sql, null, Long.class);
    }
}
